package com.lwc.cfdns.utils.file.upload;

import com.lwc.cfdns.config.AttachmentLocalConfig;
import com.lwc.cfdns.utils.SpringContextUtils;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 附件存储到本地
 *
 * @author luwc
 * @title LocalFileUploadUtils
 * @description
 * @time 2023/6/4 10:42
 * @version: 1.0
 */
public class LocalFileUpload extends AbstractFileUpload {

    /**
     * 域名或前缀
     *
     * @param
     * @return String
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/9/19 15:13:23
     */
    @Override
    public String getUploadDomain() {
        return AttachmentLocalConfig.getUploadDomain();
    }

    /**
     * 静态资源映射目录
     *
     * @param
     * @return String
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/9/19 15:43:02
     */
    public String getUploadPath() {
        return AttachmentLocalConfig.getUploadPath();
    }

    /**
     * 上传文件的保存位置
     *
     * @param
     * @return String
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/9/19 15:44:22
     */
    public String getSavePath() {
        return SpringContextUtils.getBean(MultipartProperties.class).getLocation();
    }

    /**
     * 上传单个文件
     *
     * @param file
     * @param allowedExtension
     * @return String
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/9/19 15:45:47
     */
    @Override
    public String upload(MultipartFile file, String[] allowedExtension) {
        checkFile(file, allowedExtension);
        String newPath = createPath();
        String newFileName = createFileName(file);
        File folder = new File(getSavePath() + newPath);
        Map<String, Object> map = new HashMap<>();
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        try {
            file.transferTo(new File(folder, newFileName));
            return getUploadPath() + newPath + "/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
